import axios from "axios";
import qs from "qs";
import { baseURL } from "./constants";
import nprogress from "nprogress";
import "nprogress/nprogress.css";

const instance = axios.create({
  baseURL,
  timeout: 5000,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
});

instance.interceptors.request.use((config) => {
  nprogress.start();
  return config;
});

instance.interceptors.response.use((config) => {
  nprogress.done();
  return config;
});

const request = ({ url, method = 'GET', params = {}, isMock }) => {
  return new Promise((resolve, reject) => {
    method = method.toLowerCase();
    const requestBody = method === 'get' ? 'params' : 'data';
    const format = method === 'get' ? params : qs.stringify(params);
    isMock ? instance.defaults.baseURL = '' : instance.defaults.baseURL = baseURL;
    const result = instance({ url, method, [requestBody]: format});
    result.then(value => resolve(value.data), reason => `Message.error(JSON.stringify(reason))` );
  });
};

export default request;
